<template>
  <div>
    <div class="steps">
      <el-steps :active="activeIndex" finish-status="success" simple>
        <el-step title="询报价信息" />
        <el-step title="定标信息" />
      </el-steps>
    </div>
    <!-- 供应商信息 -->
    <el-card class="sourcing-form-card">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <span>供应商信息</span>
        <div>
          <BtnRender :render="renderSupplierBtnsBar" />
        </div>
      </el-row>
      <BasicList
        :loading="quotationLoading"
        :tableMaxHeight="300"
        :data-source="supplierList"
        :columns="supplierColumns"
        :showActionCol="true"
        :actionRender="renderTableBtnAction"
        :actionColWidth="150"
        :show-pagination="false"
        :selection-change="supplerSelectionChange"
      />
    </el-card>
    <!-- 基本信息 -->
    <el-card class="sourcing-form-card">
      <div slot="header">
        <span class="ym-custom ym-custom-bookmark">基本信息</span>
      </div>
      <el-row class="box">
        <el-form ref="form" :label-width="isInqueryType() ? '110px' : '130px'">
          <el-row>
            <el-col :span="6">
              <el-form-item label="来源单据号:">
                <div>{{ basicInfo.originCode || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="询价类型:">
                <div>{{ basicInfo.billTypeName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="询价单号:">
                <div>{{ basicInfo.sourceBillNo || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上游制单人:">
                <div>{{ basicInfo.creatorName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售公司:">
                <div>{{ basicInfo.saleCompanyName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售业务员:">
                <div>{{ basicInfo.salesmanName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购询价人:">
                <div>{{ basicInfo.purchaseInquirerName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购询价部门:">
                <div>{{ basicInfo.purchaseInquirerCompanyName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="是否走手续:">
                <div>{{ basicInfo.isProceduresStr || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0" v-if="isInqueryType()">
              <el-form-item label="需求类型:">
                <div>{{ basicInfo.demandTypeStr || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="指定渠道:">
                <div>{{ basicInfo.serviceProviderName || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="是否服务商:">
                <div>{{ basicInfo.isServiceProviderStr || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0" v-if="isInqueryType()">
              <el-form-item label="发货公司:">
                <div>{{ basicInfo.shippingCompanyName || "" }}</div>
              </el-form-item>
            </el-col>
            <div v-if="!isInqueryType()">
              <el-col :span="6" :offset="0">
                <el-form-item label="收货公司:">
                  <div>{{ basicInfo.receiveCompanyName || "" }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="是否现场接货:">
                  <div>{{ basicInfo.isScenePickupStr || "" }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="能否直接联系客户:">
                  <div>{{ basicInfo.isDirectContactStr || "" }}</div>
                </el-form-item>
              </el-col>
            </div>
            <el-col :span="6" :offset="0">
              <el-form-item label="送货地址:">
                <div>{{ basicInfo.deliveryAddress || "" }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="备 注:">
                <el-input
                  v-model="basicInfo.mark"
                  placeholder="请填写备注"
                  :disabled="!canEdit()"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </el-card>
    <!-- 商品信息 -->
    <el-card class="sourcing-form-card product-info">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <span>商品信息</span>
        <div>
          <BtnRender :render="renderGoodsBtnsBar" />
        </div>
      </el-row>
      <PlTable
        :loading="quotationLoading"
        :maxTableHeight="400"
        :show-select-col="true"
        :data-source="goodsList"
        :columns="goodsColumns"
        :showActionCol="true"
        :actionRender="goodsActionRender"
        :show-pagination="false"
        :selection-change="selectionChange"
      />
      <el-row type="flex" justify="center" class="operate-area">
        <el-button v-if="!canEdit()" type="primary" @click="handleNext(1)"
          >下一步</el-button
        >
      </el-row>
    </el-card>
    <QuoteDialog
      :dialog-visible="quoteDiaVisible"
      :isSynergy="isSynergy"
      :isQuoteDone="isQuoteDone"
      @query-handler="queryQuotationDetailAction"
      @save-handler="handlesubmitQuotationForSupplier"
      @temp-handler="handleSubmitTemporaryQuotationForSupplier"
      @hide-handler="handleCancelQuote"
    />
    <QuoteViewDialog
      :dialog-visible="quoteViewDiaVisible"
      @hide-handler="handleCancelQuoteView"
    />
    <SupplierDialog
      showRecommendTab
      :dialog-visible="supplierDiaVisible"
      :sourcingBillId="queryParams.sourcingBillId"
      @hide-handler="handleCloseSupplier"
      @add-supplier="handleAddSupplier"
    />
    <AttachmentDialog
      :visible.sync="attachDialogVisible"
      :fileGroupId="viewFileId"
      :isReadOnly="isReadOnly"
    />
    <PushInquiryDialog
      :dialog-visible="pushDialogVisible"
      :dialog-data="pushInquiryList"
      :sourcingBillId="queryParams.sourcingBillId"
      :remark="basicInfo.mark"
      :skuRemarkDTOList="skuRemarkDTOList"
      @hide-handler="hanldCloseInquiry"
    />
    <!-- 修改报价有效期 -->
    <EditExpireTime
      :visible.sync="editExpireTimeVisible"
      :supplierList="selectedPushInquiryList"
      @getSupplierList="queryQuotationInfoAction"
    />
    <!-- 修改报价有效期记录 -->
    <EditExpireTimeRecord
      :visible.sync="editLogVisible"
      :sourcingBillId="queryParams.sourcingBillId"
    />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import BasicList from '../../components/BasicList';
import PlTable from '@/components/skusTable';
import QuoteDialog from './components/quoteDialog';
import QuoteViewDialog from './components/quoteViewDialog';
import SupplierDialog from '@/pages/sourcing/components/SupplierDialog'
import AttachmentDialog from '@/pages/sourcing/components/AttachmentDialog';
import PushInquiryDialog from './components/pushInquiryDialog';
import EditExpireTime from '@sourcing/components/EditExpireTime'
import EditExpireTimeRecord from '@sourcing/components/EditExpireTimeRecord'
import {
  isResponseSuccess,
  QUOTE_UNDONE_STATUS_CODE, // 报价状态 未报价 0
  QUOTE_DONE_STATUS_CODE, // 报价状态 报价完成 1
  QUOTE_PENDING_STATUS_CODE, // 报价状态 报价中 2
  QUOTE_PART_STATUS_CODE, // 报价状态 部分报价 3
} from '../utils';
import { getSupplierColumns, GOODS_COLUMNS } from './constants';
import { saveSupplierFileGroupIdService, batchExportSupplierService } from '@api/sourcing/purchaseDetail';
import { createExcelByExport } from '@/utils/bizUtils';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getTableAction, getBtnsBar } from '@sourcing/utils/renderBtn';
import {
  updateSkuCodeService,
  closeInquiryService,
} from '@/api/sourcing/purchaseDetail'

export default {
  name: 'QuoteInfo',
  components: {
    BasicList,
    QuoteDialog, // 添加报价
    QuoteViewDialog, // 添加报价查看
    SupplierDialog, // 添加供应商
    AttachmentDialog, // 查看附件
    PushInquiryDialog, // 批量推送询价单
    PlTable,
    BtnRender,
    EditExpireTime,
    EditExpireTimeRecord
  },
  data () {
    return {
      closeInquiryLoading: false,
      editExpireTimeVisible: false,
      editLogVisible: false,
      batchExportLoading: false,
      batchImportLoading: false,
      uploadLoading: false,
      viewFileId: 0,
      supplierFileId: 0,
      isReadOnly: false,
      // 是否协同供应商
      isSynergy: false,
      isQuoteDone: false,
      textTips: '您确定要删除该商品吗？删除商品后，该商品需重新发起询价，已报价信息将删除。',
      textTips2: '商品全部删除后，该采购询价单删除，需重新发起询价并重新报价，您确认吗？',
      activeIndex: 0,
      quoteDiaVisible: false,
      quoteViewDiaVisible: false,
      supplierDiaVisible: false,
      attachDialogVisible: false,
      pushDialogVisible: false,
      sourcingBillDetailsIds: [],
      pushInquiryList: [], // 批量推送询价list
      skuRemarkDTOList: [], // 推送协同供应商备注
      selectedPushInquiryList: [], // 批量推送询价list
      queryParams: {
        isEdit: '',
        pageType: '',
        sourcingBillId: '',
        isDemand: false
      },
      supplierColumns: getSupplierColumns(this),
      goodsColumns: GOODS_COLUMNS,
      uploadParams: {
        fileUploadUser: '',
        fileType: '',
        departmentId: '',
        fileGroupId: 0,
      },
      batchUploadParams: {
        dataType: 0,
        billId: ''
      }
    };
  },
  computed: {
    ...mapState('sourcing/purchaseDetail', {
      basicInfo: (state) => state.basicInfo,
      supplierList: (state) => state.supplierList,
      quotationLoading: (state) => state.quotationLoading,
      goodsList: (state) => state.goodsList,
      allSupplierInfo: (state) => state.allSupplierInfo,
      submitQuotationLoading: (state) => state.submitQuotationLoading
    }),
    // 是否勾选供应商
    notSelectSupplier () {
      return this.selectedPushInquiryList.length == 0;
    },
    // 已勾选供应商 sourcingSupplierId
    selectedSourcingSupplierIds () {
      return this.selectedPushInquiryList.map(item => item.sourcingSupplierId)
    },
    // 存在协同供应商
    hasSynergySupplier () {
      return this.selectedPushInquiryList.some(item => item.onlineCollaboration == 18913)
    }
  },
  created () {
    const detailInfo = JSON.parse(sessionStorage.getItem('detailInfo'));
    this.queryParams = { ...detailInfo };
    this.formatGoodsColumns();
    this.queryQuotationInfoAction();
  },
  methods: {
    ...mapActions('sourcing/purchaseDetail', [
      'getInqueryQuotationInfo', // 获取报价信息
      'getOrderQuotationInfo', // 获取报价信息
      'getQuotationDetail', // 获取报价明细
      'getSupplierInfo', // 获取供应商列表
      'addSupplier', // 添加供应商
      'delSupplier', // 删除供应商
      'deleteGoods', // 删除商品
      'deleteAllGoods', // 批量删除商品
      'submitQuotationForSupplier', // 供应商提交报价
      'submitTemporaryQuotationForSupplier', // 供应商暂存报价
      'submitQuotation', // 提交报价
      'getInvoiceType', // 获取发票类型
      'getTaxTate', // 获取税率
      'getFreightBearer' // 获取税率
    ]),
    // 渲染供应商按钮操作栏
    renderSupplierBtnsBar (h) {
      if (this.canEdit()) {
        const btnsBar = [
          {
            label: '修改报价有效期',
            method: this.editQuoteExpireTime,
            type: 'default',
            size: 'mini',
            disabled: this.notSelectSupplier
          },
          {
            label: '报价有效期修改记录',
            method: this.viewEditLog,
            type: 'default',
            size: 'mini',
          },
          {
            label: '批量导出',
            method: this.batchExportSupplierInfo,
            loading: this.batchExportLoading,
            type: 'default',
            size: 'mini',
            disabled: this.notSelectSupplier
          },
          {
            label: '批量导入',
            action: 'srm-api/sourceSupplier/importSupplierAndSkuQuote',
            isImport: true,
            size: 'mini',
            type: 'default',
            loadingFn: state => { this.batchImportLoading = state },
            data: { dataType: this.isInqueryType() ? 1 : 2, billId: this.queryParams.sourcingBillId }
          },
          { label: '刷新报价状态', type: 'default', size: 'mini', method: this.queryQuotationInfoAction },
          { label: '增加供应商', type: 'default', size: 'mini', method: this.handleShowSupplierDialog, },
          { label: '批量推送询价单', type: 'default', size: 'mini', method: this.handlePushInquirySheet, disabled: this.notSelectSupplier, },
          { label: '报价完成', type: 'primary', size: 'mini', method: this.handleCompleteQuotation, loading: this.submitQuotationLoading, },
        ];
        return getBtnsBar(h, btnsBar);
      }
    },
    // 渲染商品按钮
    renderGoodsBtnsBar (h) {
      if (this.canEdit()) {
        const btnsBar = [
          {
            label: '查看附件',
            method: () => { this.handleViewFileList(this.basicInfo.fileGroupId) },
            type: 'default',
            size: 'mini',
            disabled: this.basicInfo.haveFile != 1
          },
          {
            label: '查看供应商附件',
            method: () => { this.handleViewFileList(this.supplierFileId, false) },
            type: 'default',
            size: 'mini',
            disabled: !this.basicInfo.supplierFileGroupId
          },
          {
            label: '上传供应商附件',
            action: 'fts/fileUpload/upload',
            methods: { handleUploadSuccess: this.handleUploadSuccess },
            isImport: true,
            size: 'mini',
            type: 'default',
            loading: this.uploadLoading,
            loadingFn: state => { this.uploadLoading = state },
            data: { ...this.uploadParams },
            accept: []
          },
          { label: '批量删除', type: 'default', size: 'mini', method: this.handleDelAllProduct },
        ];
        return getBtnsBar(h, btnsBar);
      }
    },
    // 渲染表格操作栏按钮
    /*
      0: '未报价',
      1:'全部报价',
      2:'报价中',
      3:'部份报价',
      4:'供应商退回',
      5:'已过期',
    } */
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '查看', method: () => { this.handleQuotedPrice(row, 'view') } }
      ];
      if (this.canEdit()) {
        if (this.isSynergySupplier(row.onlineCollaboration)) {
          if (row.quoteStatus == 1) {
            actionList.push({ label: '报价', method: () => { this.handleQuotedPrice(row, 'edit') } })
          }
          if (row.quoteStatus == 0 || row.quoteStatus == 1) {
            actionList.push({ label: '推送询价', method: this.handlePushInquiryPrice })
          }
          if (row.quoteStatus !== 2 && row.quoteStatus !== 3) {
            actionList.push({ label: '删除', method: this.handleDeleteSupplier })
          }
          if (row.quoteStatus == 2 || row.quoteStatus == 3) {
            actionList.push({ label: '关闭询价单', method: () => { this.handleCloseInquiry(row) }, loading: this.closeInquiryLoading })
          }
        } else {
          actionList.push(
            { label: '报价', method: () => { this.handleQuotedPrice(row, 'edit') } },
            { label: '删除', method: this.handleDeleteSupplier }
          )
        }
      }
      return getTableAction({ h, row, actionList })
    },
    // 商品表格操作列
    goodsActionRender (h, { row }) {
      const actionList = [
        {
          label: '删除',
          method: () => { this.handleDelProduct(row, 'view') },
          disabled: !this.canEdit()
        }
      ]
      return getTableAction({ h, row, actionList })
    },
    // 修改报价有效期 已过期 协同供应商
    editQuoteExpireTime () {
      if (!this.selectedPushInquiryList.every(item => item.onlineCollaboration == 18913 && item.quoteStatus == 5)) {
        return this.$message.warning('请勾选报价状态已过期且询价单协同的供应商')
      }
      this.editExpireTimeVisible = true;
    },
    // 查看修改报价有效期记录
    viewEditLog () {
      this.editLogVisible = true;
    },
    // 批量勾选供应商
    supplerSelectionChange (data) {
      this.selectedPushInquiryList = data;
    },
    // 推送询价
    handlePushInquiryPrice (row) {
      this.pushDialogVisible = true;
      this.pushInquiryList = [row];
      this.skuRemarkDTOList = this.goodsList.map(({ sourcingBillDetailsId, supplierRemark }) => ({
        sourcingBillDetailsId,
        supplierRemark
      }))
    },
    // 批量推送询价单
    handlePushInquirySheet () {
      this.pushInquiryList = this.selectedPushInquiryList
        .filter(item => (this.isSynergySupplier(item.onlineCollaboration) && (item.quoteStatus == 0 || item.quoteStatus == 1)))
      if (this.pushInquiryList.length == 0) {
        return this.$message.warning('请勾选未报价的协同供应商。');
      }
      this.pushDialogVisible = true;
    },
    // 格式化商品表头
    formatGoodsColumns () {
      let column = {};
      if (this.isInqueryType()) {
        column = {
          key: 'reqSourcingDate',
          title: '要求采购询价时间',
          width: 150
        };
      } else {
        column = {
          key: 'reqArrivalDate',
          title: '要求到货时间',
          width: 120
        };
      }
      // 如果不存在 要求到货时间 则添加
      if (!this.goodsColumns.find(item => item.key == column.key)) {
        this.goodsColumns.push(column);
      }
    },
    // 获取报价信息
    queryQuotationInfoAction () {
      const data = {
        sourcingBillId: this.queryParams.sourcingBillId
      };
      const cb = (res) => {
        const { supplierFileGroupId } = res.data.base;
        this.supplierFileId = supplierFileGroupId || 0;
        this.getUploadParams()
      }
      if (this.isInqueryType()) {
        this.getInqueryQuotationInfo({
          payload: {
            data,
            cb
          }
        });
      } else {
        this.getOrderQuotationInfo({
          payload: {
            data,
            cb
          }
        });
      }
    },
    // 获取报价详情
    queryQuotationDetailAction (row, type) {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          const { checkType = '', msg = '' } = res.data
          if (checkType) {
            this.$confirm(`${msg}`, '提示', {
              type: 'warning',
            }).then(() => {
              // 线索商品为一物多码商品（确认的话调用指定接口：）
              this.handleUpdateSkuCode()
            }).catch(() => {})
          } else {
            if (type == 'view') {
              this.quoteViewDiaVisible = true;
            } else {
              this.quoteDiaVisible = true;
              this.isSynergy = this.isSynergySupplier(row.onlineCollaboration);
              this.isQuoteDone = row.quoteStatus == QUOTE_DONE_STATUS_CODE;
            }
          }
        }
      };
      const data = {
        sourceBillId: this.queryParams.sourcingBillId,
        sourceSupplierId: row.sourcingSupplierId
      };
      this.getQuotationDetail({
        payload: {
          data,
          cb
        }
      });
    },
    // 获取发票类型 521、税率 10100、运费承担方集合 10146
    queryInvoiceTypeAction () {
      this.getInvoiceType({
        payload: {
          data: { sysTypeClassId: '521' }
        }
      });
      this.getTaxTate({
        payload: {
          data: { sysTypeClassId: '10100' }
        }
      });
      this.getFreightBearer({
        payload: {
          data: { sysTypeClassId: '10146' }
        }
      });
    },
    // 添加供应商
    addSupplierAction (param) {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success(res.msg);
          this.supplierDiaVisible = false;
          this.queryQuotationInfoAction();
        }
      };
      const data = {
        sourceBillId: this.queryParams.sourcingBillId,
        supplierList: param
      };
      this.addSupplier({
        payload: {
          data,
          cb
        }
      });
    },
    // 删除供应商
    deleteSupplierAction (row) {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success(res.msg);
          this.queryQuotationInfoAction();
        }
      };
      const data = {
        sourcingSupplierId: row.sourcingSupplierId
      };
      this.delSupplier({
        payload: {
          data,
          cb
        }
      });
    },
    // 为供应商添加报价
    submitQuotationForSupplierAction (params) {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success(res.msg);
          this.quoteDiaVisible = false;
          this.queryQuotationInfoAction();
        }
      };
      const data = {
        ...params
      };
      this.submitQuotationForSupplier({
        payload: {
          data,
          cb
        }
      });
    },
    // 为供应商暂存报价
    submitTemporaryQuotationForSupplierAction (params) {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success(res.msg);
          this.quoteDiaVisible = false;
          this.queryQuotationInfoAction();
        }
      };
      const data = {
        ...params
      };
      this.submitTemporaryQuotationForSupplier({
        payload: {
          data,
          cb
        }
      });
    },
    // 删除商品
    deleteGoodsAction (row) {
      const data = {
        sourcingBillDetailsId: row.sourcingBillDetailsId
      };
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success('删除商品成功');
          this.queryQuotationInfoAction();
        }
      };
      this.deleteGoods({
        payload: {
          data,
          cb
        }
      });
    },
    // 批量删除
    selectionChange (data) {
      const idArr = [];
      this.sourcingBillDetailsIds = [];
      if (data.length !== 0) {
        data.forEach((item) => {
          idArr.push(item.sourcingBillDetailsId);
        });
        this.sourcingBillDetailsIds = idArr;
      }
    },
    deleteAllGoodsAction () {
      const data = this.sourcingBillDetailsIds;
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          this.$message.success('删除商品成功');
          this.queryQuotationInfoAction();
        }
      };
      this.deleteAllGoods({
        payload: {
          data,
          cb
        }
      });
    },
    handleDelAllProduct () {
      if (this.sourcingBillDetailsIds.length == 0) {
        return this.$message.warning('请勾选要删除的商品');
      }
      this.$confirm(this.goodsList.length == this.sourcingBillDetailsIds.length ? this.textTips2 : this.textTips, '提示', {
        type: 'warning'
      })
        .then(() => {
          this.deleteAllGoodsAction();
        })
        .catch(() => {});
    },
    // 供应商表格查看附件
    handleViewFileList (fileId, isReadOnly = true) {
      this.viewFileId = fileId;
      this.isReadOnly = isReadOnly;
      this.attachDialogVisible = true;
    },
    /* 供应商 - 供应商 - 供应商 */
    // 显示供应商弹框
    handleShowSupplierDialog () {
      if (this.goodsList.length === 0) {
        return this.$message.warning('商品不存在，无需添加供应商');
      }
      if (this.supplierList && this.supplierList.length >= 10) {
        return this.$message.warning('供应商数量最多10个！');
      }
      this.supplierDiaVisible = true;
    },
    // 添加供应商
    handleAddSupplier (param) {
      const supplierListLength = this.supplierList.length || 0;
      const paramLength = param.length || 0;
      if (supplierListLength + paramLength > 10) {
        return this.$message.warning('供应商数量最多10个！');
      }
      this.addSupplierAction(param);
    },
    // 删除供应商
    handleDeleteSupplier (row) {
      this.$confirm('您确定要删除该供应商吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.deleteSupplierAction(row);
        })
        .catch(() => {});
    },
    // 关闭询价单
    handleCloseInquiry (row) {
      this.$confirm('关闭询价单后，供应商将无法报价，您确认要提前关闭询价单吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.closeInquiryAction(row.sourcingSupplierId)
        })
        .catch(() => {});
    },
    async closeInquiryAction (sourcingSupplierId) {
      const res = await closeInquiryService(
        { sourcingSupplierId },
        state => { this.closeInquiryLoading = state }
      )
      if (res) {
        this.$message.success('操作成功')
        this.queryQuotationInfoAction()
      }
    },
    // 点击报价
    handleQuotedPrice (row, type) {
      this.queryInvoiceTypeAction();
      this.queryQuotationDetailAction(row, type);
    },
    // 为供应商添加报价
    handlesubmitQuotationForSupplier (params) {
      this.submitQuotationForSupplierAction(params);
    },
    // 为供应商暂存报价
    handleSubmitTemporaryQuotationForSupplier (params) {
      this.submitTemporaryQuotationForSupplierAction(params);
    },
    // 取消报价
    handleCancelQuote () {
      this.quoteDiaVisible = false;
    },
    // 取消报价查看
    handleCancelQuoteView () {
      this.quoteViewDiaVisible = false;
    },
    // 关闭添加供应商弹框
    handleCloseSupplier () {
      this.supplierDiaVisible = false;
    },
    // 删除商品
    handleDelProduct (row) {
      this.$confirm(
        this.goodsList.length == 1 ? this.textTips2 : this.textTips,
        '提示',
        {
          type: 'warning'
        }
      )
        .then(() => {
          this.deleteGoodsAction(row);
        })
        .catch(() => {});
    },
    // 报价完成 - 提交报价
    handleSubmitQuotation () {
      const cb = (res) => {
        if (isResponseSuccess(res)) {
          if (res.data) {
            this.$confirm(`${res.data}`, '提示', {
              type: 'warning',
            }).then(() => {
              // 线索商品为一物多码商品（确认的话调用指定接口：）
              this.handleUpdateSkuCode()
            }).catch(() => {})
          } else {
            this.handleNext(0);
          }
        }
      };
      this.submitQuotation({
        payload: {
          data: {
            sourcingBillId: this.queryParams.sourcingBillId,
            mark: this.basicInfo.mark
          },
          cb
        }
      });
    },
    // 线索商品为一物多码商品
    async handleUpdateSkuCode () {
      const res = await updateSkuCodeService({ sourcingBillId: this.queryParams.sourcingBillId }, state => { this.submitQuotationLoading = state })
      if (res) {
        this.$message.success('操作成功')
        this.queryQuotationInfoAction()
      }
    },
    // 关闭批量询价弹框
    hanldCloseInquiry (data) {
      this.pushDialogVisible = false;
      if (data && data.success) {
        this.queryQuotationInfoAction()
      }
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
    // 下一步
    handleNext (val) {
      // isCompleteWinBill 定标完成：1，未完成：0；
      sessionStorage.setItem('isCompleteWinBill', val);
      if (this.isInqueryType()) {
        this.$router.push({ name: 'demandCalibrationDetail' });
      } else {
        if (this.canEdit()) {
          this.$router.push({ name: 'orderCalibration' });
        } else {
          this.$router.push({ name: 'orderCalibrationView' });
        }
      }
    },
    // 报价完成
    handleCompleteQuotation () {
      if (!this.supplierList || this.supplierList.length === 0) {
        return this.$message.warning('供应商数量最少为1个，最多10个!');
      }
      // 不能完成报价状态集合
      const status = [ QUOTE_UNDONE_STATUS_CODE, QUOTE_PENDING_STATUS_CODE, QUOTE_PART_STATUS_CODE ];
      const hasNotQuote = this.supplierList.some(
        (item) => status.includes(item.quoteStatus)
      );
      if (hasNotQuote) {
        return this.$message.warning('存在报价状态为未报价、部分报价、报价中的供应商,不能报价完成');
      }
      this.handleSubmitQuotation();
    },
    // 是否可编辑
    canEdit () {
      return this.queryParams.isEdit === true;
    },
    // 是否为询价页面
    isInqueryType () {
      return this.queryParams.pageType === 1;
    },
    // 是否为需求管理
    isDemand () {
      return this.queryParams.isDemand;
    },
    // 是否为协同供应商
    isSynergySupplier (type) {
      // 原字段onlineCollaboration 18913为是，18914为否
      return type == 18913;
    },
    // 上传成功
    handleUploadSuccess (res) {
      if (res.code == 0) {
        if (!this.supplierFileId) {
          const param = {
            sourcingBillId: this.queryParams.sourcingBillId,
            supplierFileGroupId: res.fileGroupId,
          }
          this.handleSaveFileGroupId(param)
        } else {
          this.queryQuotationInfoAction()
        }
      } else {
        this.$message.error(res.msg || '上传异常')
      }
    },
    // 保存供应商附件ID
    async handleSaveFileGroupId (data) {
      const res = await saveSupplierFileGroupIdService(data)
      if (res) {
        this.queryQuotationInfoAction()
      }
    },
    // 获取用户信息
    getUploadParams () {
      if (!localStorage.getItem('userInfo')) {
        return this.$message.error('获取用户信息失败，请退出重新登录')
      }
      const { userId, userName } = JSON.parse(localStorage.getItem('userInfo'));
      this.uploadParams = {
        fileUploadUser: userId,
        fileUploadUserName: userName,
        departmentId: -1,
        fileType: this.isInqueryType() ? 20 : 30,
        fileGroupId: this.supplierFileId
      }
    },
    // 批量导出供应商信息
    async batchExportSupplierInfo () {
      if (this.hasSynergySupplier) {
        return this.$message.warning('协同供应商不能导出，请取消勾选');
      }
      const data = {
        billId: this.queryParams.sourcingBillId,
        dataType: this.isInqueryType() ? 1 : 2,
        sourcingSupplierIdList: this.selectedSourcingSupplierIds
      }
      const res = await batchExportSupplierService(data, state => { this.batchExportLoading = state })
      if (res) {
        createExcelByExport({ res, excelTitle: '供应商信息' });
      }
    },
  }
};
</script>

<style lang="less" scoped>
.show {
  display: block;
}
.hide {
  display: none;
}
.operate-area {
  margin: 15px 15px 40px 15px;
}
</style>>
